import { useState, useEffect } from 'react';
import { Permission, UserInfo } from './simple';
import { DynamicPermissionChecker } from './DynamicPermissionChecker';
import { RoleService } from './RoleService';

/**
 * 使用动态权限的React Hook
 */
export function useDynamicPermissions(user: UserInfo) {
  const [permissions, setPermissions] = useState<Permission[]>([]);
  const [roleConfig, setRoleConfig] = useState<any>(null);
  const [manageableRoles, setManageableRoles] = useState<string[]>([]);
  const [roleNames, setRoleNames] = useState<Record<string, string>>({});
  const [roleColors, setRoleColors] = useState<Record<string, string>>({});
  const [loading, setLoading] = useState(true);
  
  const roleService = RoleService.getInstance();
  const checker = new DynamicPermissionChecker(user);
  
  // 加载权限和角色配置
  useEffect(() => {
    const loadPermissions = async () => {
      setLoading(true);
      try {
        // 加载用户权限
        const userPermissions = await checker.getUserPermissions();
        setPermissions(userPermissions);
        
        // 加载用户角色配置
        const config = await roleService.getRoleConfig(user.roleType);
        setRoleConfig(config);
        
        // 加载可管理的角色
        const manageable = await checker.getManageableRoles();
        setManageableRoles(manageable);
        
        // 加载所有角色配置
        const allRoleConfigs = await roleService.getAllRoleConfigs();
        
        // 设置角色名称和颜色映射
        const names: Record<string, string> = {};
        const colors: Record<string, string> = {};
        
        for (const [roleType, config] of Object.entries(allRoleConfigs)) {
          if (config.enabled) {
            names[roleType] = config.name;
            colors[roleType] = config.color;
          }
        }
        
        setRoleNames(names);
        setRoleColors(colors);
      } catch (error) {
        console.error('加载权限配置失败:', error);
      } finally {
        setLoading(false);
      }
    };
    
    loadPermissions();
  }, [user.roleType, user.id]);
  
  // 基础权限检查，同步版本
  const hasPermissionSync = (permission: Permission): boolean => {
    return permissions.includes(permission);
  };
  
  return {
    // 同步方法（使用预加载的数据）
    hasPermission: hasPermissionSync,
    permissions,
    roleConfig,
    manageableRoles,
    roleNames,
    roleColors,
    loading,
    
    // 异步方法（实时检查）
    hasPermissionAsync: (permission: Permission) => checker.hasPermission(permission),
    canAccessLevel: (level: number) => checker.canAccessLevel(level),
    canManageRole: (role: string) => checker.canManageRole(role),
    
    // 角色工具方法
    getVisibleRoleOptions: () => roleService.getVisibleRoleOptions(),
    
    // 重新加载方法
    reload: async () => {
      await roleService.loadRoles(true);
      const userPermissions = await checker.getUserPermissions();
      setPermissions(userPermissions);
    }
  };
} 